﻿#region Copyright and License
/*==============================================================================
 *  Copyright (c) www.51mvc.com Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.51mvc.com/
 * Create By 小鱼(Leven)  - http://leven.com.cn
 * ==============================================================================*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Infancy.Core.Validation {
    /// <summary>
    /// 指示该属性是否能为空
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class NullableValidateAttribute : ValidateAttributeBase {
        /// <summary>
        /// 是否能为空
        /// </summary>
        public bool CanNull { get; protected set; }

        public NullableValidateAttribute()
            : this(true) {
        }

        public NullableValidateAttribute(bool cannull) {
            CanNull = cannull;
            Message = "该项不能为空";
        }

        public override ValidatedResult Execute(ValidateContext context) {
            bool result = CanNull;
            if (!CanNull) {
                if (context.Value is String) {
                    result = result | !String.IsNullOrEmpty(context.Value as String);
                } else {
                    result = result | context.Value != null;
                }
            }
            ValidatedResult vr = new ValidatedResult(result);
            if (!result)
                vr.Errors.Add(context.Name, Message);
            return vr;
        }
    }
}
